package com.wedo.auth.service;

import com.netflix.discovery.converters.Auto;
import com.wedo.admin.pojo.Admin;
import com.wedo.auth.client.AdminClient;
import com.wedo.auth.client.UserClient;
import com.wedo.auth.config.JwtProperties;
import com.wedo.auth.pojo.UserInfo;
import com.wedo.auth.utils.JwtUtils;
import com.wedo.user.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthService {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AdminClient adminClient;

    @Autowired
    private UserClient userClient;

    /**
     * 根据用户名密码获取jwt
     * @param username
     * @param password
     * @return
     */
    public String accredit(String username, String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return null;
        }
        // 根据用户名密码查询
        User user = this.userClient.queryByUsernameAndPassword(username,password);
        // 判断用户是否为空
        return getJwtString(user);
    }

    /**
     * 根据手机号码验证码获取jwt
     * @param phone
     * @param code
     * @return
     */
    public String accreditByPhone(String phone, String code) {
        // 根据手机号和手机验证码查询
        User user = this.userClient.queryByPhoneAndCode(phone, code);
        return getJwtString(user);
    }

    private String getJwtString(User user) {
        // 判断用户是否为空
        if (user == null) {
            return null;
        }
        try {
            // jwtUtils生成jwt类型的token
            UserInfo userInfo = new UserInfo();
            userInfo.setId(user.getId());
            userInfo.setUsername(user.getUsername());
            userInfo.setPhone(user.getPhone());
            return JwtUtils.generateToken(userInfo,jwtProperties.getPrivateKey(),this.jwtProperties.getExpire());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 获取管理员的jwt
    public String getAdminJwt(String adminName, String password) {
        Admin admin = adminClient.queryByAdminName(adminName, password);

        // 判断admin是否为空
        if (admin == null) {
            return null;
        }
        try {
            // jwtUtils生成jwt类型的token
            UserInfo userInfo = new UserInfo();
            userInfo.setId(admin.getId());
            userInfo.setUsername(admin.getAdminName());
            userInfo.setRole("ADMIN");
            return JwtUtils.generateToken(userInfo,jwtProperties.getPrivateKey(),this.jwtProperties.getExpire());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
